#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/1/1 0:20
# @Author  : leon yan
# @Site    : 
# @File    : fileprocess.py
# @Software: PyCharm

import json
import os
import sys
from xml.etree import ElementTree

from PyQt5.Qt import QObject, QFileDialog, QItemDelegate


# 空代理，主要为了禁止tableview某列禁止修改
class EmptyDelegate(QItemDelegate):
    def __init__(self, parent):
        super(EmptyDelegate, self).__init__(parent)

    def createEditor(self, QWidget, QStyleOptionViewItem, QModelIndex):
        return None


# 用于处理xml文件--标签文件
class xmlProcess(QObject):
    @classmethod
    def openXmlfile(cls):
        try:
            curPath = os.getcwd()  # 获取当前路径
            filename, flt = QFileDialog.getOpenFileName(None, "打开一个文件", curPath,
                                                        "xml(*.xml)")
            # filename, flt = QFileDialog.getOpenFileName(None,"打开一个文件", curPath,
            #                                                      "xml(*.xml);;cyc(*.cyc)")
        except Exception as e:
            print('打开失败', e)
        else:
            return filename

    @classmethod
    def openCycfile(cls):
        try:
            curPath = os.getcwd()  # 获取当前路径
            filename, flt = QFileDialog.getOpenFileName(None, "打开一个文件", curPath,
                                                        "cyc(*.cyc)")
            # filename, flt = QFileDialog.getOpenFileName(None,"打开一个文件", curPath,
            #                                                      "xml(*.xml);;cyc(*.cyc)")
        except Exception as e:
            print('打开失败', e)
        else:
            return filename

    # 处理xml不能显示问题，未使用
    @classmethod
    def change_file_to_xml(cls, filepath):
        oldfile = open(filepath, 'r')
        newfile = open('temp.xml', 'w')
        for line in oldfile:
            if "xml-stylesheet" in line:
                continue
            newfile.write(line)
            print(line)
        return newfile

    # 获取子元素的子元素值
    @classmethod
    def getchildren_list(cls, father_node, node_name):
        list = []
        for i in father_node.find(node_name).getchildren():
            list.append(i.text)
        return list

    # 解析xml
    @classmethod
    def read_xml(cls, newxml):
        xml_dic = {}
        root = ElementTree.parse(newxml).getroot()
        id = 0
        for Case in root.findall('Cycle'):
            id += 1
            case_dic = {}
            Field_list = []  # 是一个元组数据
            for i in Case.findall('Field'):
                Field_list.append(i.attrib)
            case_dic['Field_list'] = Field_list
            xml_dic[id] = case_dic
        return xml_dic


class jsonProcess(QObject):
    @classmethod
    def get_stored_data(self, filename):
        try:
            with open(filename) as f_obj:
                storedData = json.load(f_obj)
        except FileNotFoundError:
            return None
        else:
            return storedData

    @classmethod
    def get_stored_JsonData(self, filename):
        try:
            with open(filename) as f_obj:
                storedData = json.load(f_obj)["data"]
        except FileNotFoundError:
            return None
        else:
            return storedData

    @classmethod
    def set_stored_data(cls, path, datalist):
        # 判断目录是否存在
        # print(datalist)
        # curPath = os.getcwd()
        # bbb = '%s%s'%(curPath, path)
        if not os.path.exists(os.path.split(path)[0]):
            # 目录不存在创建，makedirs可以创建多级目录
            os.makedirs(os.path.split(path)[0])
        try:
            # 保存数据到文件
            with open(path, 'w') as f_obj:
                json.dump(datalist, f_obj)
        except Exception as e:
            print('保存失败', e)

    @classmethod
    def set_stored_json(cls, path, datalist):  # DICT_TO_JSON
        # 判断目录是否存在
        # print(datalist)
        # curPath = os.getcwd()
        # bbb = '%s%s'%(curPath, path)
        if not os.path.exists(os.path.split(path)[0]):
            # 目录不存在创建，makedirs可以创建多级目录
            os.makedirs(os.path.split(path)[0])
        try:
            # 保存数据到文件
            # jsonContext["data"] = subValue
            # jsonData = json.dumps(jsonContext, indent=4, separators=(',', ': '))
            jsonContext = {"data": datalist}
            jsonData = json.dumps(jsonContext, indent=4, separators=(',', ': '))
            fObj = open(path, 'w')
            fObj.write(jsonData)
        except Exception as e:
            print('保存失败', e)


# 用于处理读写INI配置文件，保存和读取通信参数等信息
class iniProcess(QObject):
    # 读文件Ini
    @classmethod
    def readInifile(cls, filename):
        lines = []
        if os.path.isfile(filename):
            with open(filename, 'r') as file_to_read:
                while True:
                    line = file_to_read.readline()
                    if not line:
                        break
                    line = line.strip('\n')
                    line = line.split("=")
                    if len(line) == 2:
                        lines.append(line[1])
        else:
            cls.writeInifile("@@", filename)
        return lines

    # 写文件Ini
    @classmethod
    def writeInifile(cls, parStr, filename):
        with open(filename, 'w') as file_object:
            file_object.write(str(parStr))


class cfgProcess(QObject):
    @classmethod
    def readNcFile(cls, filename):
        lines = []
        if os.path.isfile(filename):
            with open(filename, 'r') as file_to_read:
                while True:
                    line = file_to_read.readline()
                    if not line:
                        break
                    line = line.strip('\n')
                    lines.append(line)
        return lines

    @classmethod
    def writeNcFile(cls, parStr, filename):
        with open(filename, 'w') as file_object:
            file_object.write(str(parStr))

    @classmethod
    def get_cfg_JsonData(self, filename):
        try:
            with open(filename, encoding="utf-8") as f_obj:
                storedData = json.load(f_obj)
        except FileNotFoundError:
            return None
        else:
            return storedData

    @classmethod
    def set_cfg_json(cls, path, dataDict):  # DICT_TO_JSON
        if not os.path.exists(os.path.split(path)[0]):
            os.makedirs(os.path.split(path)[0])
        try:
            jsonContext = dataDict
            jsonData = json.dumps(jsonContext, indent=4, separators=(',', ': '))
            fObj = open(path, 'w')
            fObj.write(jsonData)
        except Exception as e:
            print('保存失败', e)


if __name__ == '__main__':
    pass
    # jsonProcess.set_stored_data("a", "b")
    # print(jsonProcess.get_stored_data(r"\tempTotalList.json"))
    # print(xmlProcess.read_xml("List_2016.xml"))
